import React from "react";
import { Modal, ModalContent, ModalHeader, ModalBody, ModalFooter, Button } from "@nextui-org/react";
import ToastUtil from "@/app/utils/toastUtil";
import PubSub from "pubsub-js";
import { deleteNote } from "@/app/service/noteService";
import createAxiosClient from "@/app/utils/axiosRequest";

/**
 * 删除笔记弹窗服务
 */
export default function DelNoteService({ isOpenDelNote, onOpenChangeDelNote, noteId, onDeleteSuccess }: {
  isOpenDelNote: boolean;
  onOpenChangeDelNote: (isOpen: boolean) => void;
  noteId: number;
  onDeleteSuccess?: () => void;
}) {
  // 引入axios
  const axiosInstance = createAxiosClient();
  
  // 删除笔记
  async function delNote() {
    try {
      const success = await deleteNote(noteId);
      
      if (success) {
        // 关闭弹窗
        onOpenChangeDelNote(false);
        
        // 发布消息更新列表
        PubSub.publish('refreshNote', true);
        
        // 调用删除成功回调
        if (onDeleteSuccess) {
          onDeleteSuccess();
        }
      }
    } catch (error: any) {
      ToastUtil(error.message || "删除操作异常", "❌", "error");
    }
  }
  
  return (
    <Modal isOpen={isOpenDelNote} onOpenChange={onOpenChangeDelNote} backdrop="blur">
      <ModalContent>
        {(onClose) => (
          <>
            <ModalHeader className="flex flex-col gap-1">删除笔记</ModalHeader>
            <ModalBody>
              <p>确定要删除这篇笔记吗？此操作无法撤销。</p>
            </ModalBody>
            <ModalFooter>
              <Button color="default" variant="light" onPress={onClose}>
                取消
              </Button>
              <Button color="danger" onPress={delNote}>
                删除
              </Button>
            </ModalFooter>
          </>
        )}
      </ModalContent>
    </Modal>
  );
}